import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class HallDaoImpl implements HallDao {

    @Override
    public boolean addHall(Hall hall) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO hall VALUES (?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, hall.getHallName());
            pstmt.setInt(2, hall.getRowCount());
            pstmt.setInt(3, hall.getColCount());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtil.closeResources(conn, pstmt, null);
        }
    }

    @Override
    public List<Hall> getAllHalls() {
        List<Hall> halls = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM hall";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Hall hall = new Hall(
                    rs.getString("hall_name"),
                    rs.getInt("row_count"),
                    rs.getInt("col_count")
                );
                halls.add(hall);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResources(conn, pstmt, rs);
        }
        return halls;
    }

    @Override
    public Hall getHallByName(String hallName) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM hall WHERE hall_name = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, hallName);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                return new Hall(
                    hallName,
                    rs.getInt("row_count"),
                    rs.getInt("col_count")
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeResources(conn, pstmt, rs);
        }
        return null;
    }
}
    